<template>
  <div class="wrap">
    <!-- 总数 -->
    <div class="total">
      {{total}}
    </div>

    <!-- 硬币 -->
    <div class="ying-bi-container">
      <ying-bi 
        v-for="(item, index) in yingBiList"
        :key="index"
        :isSpin="item.isSpin"
        :num="item.num"
      />
    </div>

    <!-- 已经有结果的硬币数 -->
    <div>
      {{count}}/3
    </div>

    <!-- 控制按钮 -->
    <el-button 
      type="primary"
      @click="handleClick"
    >开始</el-button>

  </div>
</template>

<script>
import YingBi from "./YingBi.vue"

export default {
  components: { YingBi },

  data(){
    return {
      yingBiList: []
    }
  },

  props:['yaoCount'],

  computed: {
    // 已经确定了结果的硬币数量
    count(){
      return this.yingBiList.reduce((sum, cur) => {
        let temp = 0
        if(cur.num !== '待定') {
          temp = 1
        } 
        return sum + temp
      }, 0)
    }, 
    
    // 三枚硬币的总数
    total(){
      return this.yingBiList.reduce((sum, cur) => {
        let temp = 0
        if(cur.num !== '待定'){
          temp = cur.num 
        }
        return sum + temp
      }, 0)
    },  
  },

  created(){
    this.init()
  },

  methods: {
    async handleClick(){
      if(this.yaoCount == 6){
        this.$emit('init')
      }
      this.init()
      await this.spin(this.yingBiList[0], this.randomTime())
      await this.spin(this.yingBiList[1], this.randomTime())
      await this.spin(this.yingBiList[2], this.randomTime())
      this.$emit('updateYaoList', this.total)
    },

    // 初始化
    init(){
      // 清空
      this.yingBiList = []

      let yingBi = {
        isSpin: false,
        num: '待定'
      }
      for(let i = 0 ; i < 3 ; i++){
        let temp = JSON.parse(JSON.stringify(yingBi))
        this.yingBiList.push(temp)
      }
    },

    // 获取随机时间
    randomTime(){
      return 1000 + ~~(Math.random()*1000)
    },

    // 旋转某一硬币
    async spin(yingBi, time){
      const self = this
      return new Promise(resolve => {
        yingBi.isSpin = true // 启动旋转
        setTimeout(()=>{
          resolve()
          self.settle(yingBi)
        }, time)
      })
    },

    // 设置一个硬币的最终状态
    settle(yingBi){
      yingBi.num = this.getNum()
      yingBi.isSpin = false
    },

    // 获取硬币的值 
    getNum(){
      return Math.random() > 0.5 ? 3 : 2
    }
  }
}
</script>

<style scoped>
.wrap {
  display: flex;
  flex-direction: column;
  width: 450px;
  height: 350px;
  align-items: center;
  justify-content: space-between;
  border: 1px solid #ccc;
  padding: 20px;
  margin-left: 20px;
  margin-right: 40px;
}

.ying-bi-container {
  display: flex;
  width: 400px;
  justify-content: space-between;
}

.total {
  font-size: 20px;
  font-weight: 600;
}
</style>